package com.om39a.plm.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.om39a.plm.parser.ParserFollowersPage;

/**
 * @author om39a
 * 
 */
public class PLMFileUtils {
	static Logger logger = Logger.getLogger(PLMFileUtils.class);
	private File fileDir;

	public PLMFileUtils(String fileLocation) throws IOException {
		fileDir = new File(fileLocation);
	}

	public String readFile() throws IOException {
		logger.info("Entering to readFile");
		StringBuffer buffer = new StringBuffer();
		FileInputStream fstream = new FileInputStream(fileDir);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null) {
			buffer.append(strLine);
			buffer.append("\r\n");
		}
		in.close();
		logger.info("Exiting from readFile");
		return buffer.toString();
	}

	public List<String> readFileToList() throws IOException {
		logger.info("Entering to readFileToList");
		List<String> buffer = new ArrayList<String>();
		FileInputStream fstream = new FileInputStream(fileDir);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null) {
			buffer.add(strLine);
		}
		in.close();
		logger.info("Exiting from readFileToList");
		return buffer;
	}

	public Set<String> readFileToSet() throws IOException {
		logger.info("Entering to readFileToSet");
		Set<String> buffer = new HashSet<String>();
		FileInputStream fstream = new FileInputStream(fileDir);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null) {
			buffer.add(strLine);
		}
		in.close();
		logger.info("Exiting from readFileToSet");
		return buffer;
	}

	public void writeToFile(String content) throws IOException {
		logger.info("Entering to writeToFile");
		if (!fileDir.exists()) {
			fileDir.createNewFile();
		}
		FileWriter fileWritter = new FileWriter(fileDir.getName(), true);
		BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
		bufferWritter.write(content);
		bufferWritter.write("\n");
		bufferWritter.close();
		logger.info("Exiting from writeToFile");
	}

}
